<?php
header("Content-type: text/html; charset=utf-8");
ini_set('display_errors', 1);
set_time_limit(0);
include_once dirname(dirname(__FILE__)) . '/mgtv_init.php';
include_once dirname(dirname(__FILE__)) . '/models/public_model_exec.class.php';

class timer_clip_redis_queue extends nn_timer
{
	//获取条数
	public $task_num = 100;
	public $log_module = "clip_redis_queue";
	
	public function action($params = null)
	{
		$this->msg('开始执行...');
		$this->do_timer_action();
		$this->msg('执行结束...');
	}
	/**
	 * 执行体
	 */
	public function do_timer_action()
	{
		$redis_obj = nl_get_redis();
		$obj = $redis_obj->get_redis();
		if(!isset($obj->socket))
		{
			nn_log::write_log_message('clip_log', 'redis连接异常', '',$this->log_module);
			return ;
		}
		//获取所有SP
		$sp_list = sp_model::get_sp_list();
		if (is_array($sp_list) && $sp_list != null)
		{
			foreach ($sp_list as $sp_info)
			{
				$sp_config = json_decode($sp_info['nns_config'],true);
				if(isset($sp_config['clip_pre_max']) && (int)$sp_config['clip_pre_max'] > 0)
				{
					$this->task_num = $sp_config['clip_pre_max'];
				}
				nn_log::write_log_message('clip_log', '获取任务：' . var_export($this->task_num, true), $sp_info['nns_id'],$this->log_module);
				//循环获取任务进入redis
				for ($sin=0;$sin<$this->task_num;$sin++)
				{
					$task_info = clip_task_model::get_task($sp_info['nns_id']);
					nn_log::write_log_message('clip_log', '获取到任务：' . var_export($task_info, true), $sp_info['nns_id'],$this->log_module);
					if (!is_array($task_info))
					{
						continue;
					}				
					//存入redis
					$bool = $redis_obj->rpush($sp_info['nns_id'], $task_info['nns_content']);
					if (!$bool)
					{
						nn_log::write_log_message('clip_log', '任务存入redis失败', $sp_info['nns_id'],$this->log_module);
						continue;
					}
					//更新任务状态:任务已被取走
					$set_state = array (
							'nns_state' => clip_task_model::TASK_C_STATE_HANDLE,
							'nns_desc' => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_HANDLE],
							'nns_start_time' => date('Y-m-d H:i:s'),
							'nns_modify_time' => date('Y-m-d H:i:s'),
							'nns_new_dir' => 0
					);
					nn_log::write_log_message('clip_log', '更新内容：' . var_export($set_state, true), $sp_info['nns_id'],$this->log_module);
					
					clip_task_model::update_task($task_info['nns_id'], $set_state);
					//任务日志
					$task_log = array (
							'nns_task_id' => $task_info['nns_id'],
							'nns_state' => clip_task_model::TASK_C_STATE_HANDLE,
							'nns_desc' => clip_task_model::$task_state_arr[clip_task_model::TASK_C_STATE_HANDLE]
					);
					nn_log::write_log_message('clip_log', '任务日志内容：' . var_export($task_log, true), $sp_info['nns_id'],$this->log_module);
					clip_task_model::add_task_log($task_log);					
				}			
			}
		}
	}
}

$arr_files = pathinfo(__FILE__);
$file_name = $arr_files['filename'];
$timer_execute = new timer_clip_redis_queue($file_name, '',__FILE__);
$timer_execute->run();